package com.movisol.messengercommunicator;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.content.Context;

import com.movisol.messengercommunicator.data.CommunicatorRoot;
import com.movisol.messengercommunicator.events.DataLoadedEvent;
import com.movisol.messengercommunicator.ilisteners.IConversationsListLoaded;
import com.movisol.messengercommunicator.ilisteners.IMessagePosted;
import com.movisol.messengercommunicator.ilisteners.IMessagesListLoaded;
import com.movisol.tools.HelperUtils;

public class CommunicatorMock {
	
	Context context = null;
	protected List<IConversationsListLoaded> conversationListLoadedListeners = new ArrayList<IConversationsListLoaded>();
	protected List<IMessagesListLoaded> messagesListLoadedListeners = new ArrayList<IMessagesListLoaded>();
	protected List<IMessagePosted> messagePostedListeners = new ArrayList<IMessagePosted>();
	
	public CommunicatorMock(Context context)
	{
		this.context = context;
	}
	
	
	/******************ConversationListLoaded*****************/
	public synchronized void addConversationListLoadedListener(IConversationsListLoaded listener){
		
		conversationListLoadedListeners.add(listener);
	}
	
	
	public synchronized void removeConversationListLoadedListener(IConversationsListLoaded listener){
		
		conversationListLoadedListeners.remove(listener);
	}
	
	
	/**
	 * Fires all the Events for all the listener subscribed
	 */
	public void fireConversationsListLoaded(String error){
		
		DataLoadedEvent dle = null;
		dle = new DataLoadedEvent(this, error);
		Iterator<IConversationsListLoaded> it = conversationListLoadedListeners.listIterator();
		while (it.hasNext()){
			 it.next().conversationListLoaded(dle);
		}
	}
	/********************************************************/
	
	
	
	/******************MessagesListLoaded*****************/
	public synchronized void addMessagesListLoadedListener(IMessagesListLoaded listener){
		
		messagesListLoadedListeners.add(listener);
	}
	
	
	public synchronized void removeMessagesListLoadedListener(IMessagesListLoaded listener){
		
		messagesListLoadedListeners.remove(listener);
	}
	
	
	/**
	 * Fires all the Events for all the listener subscribed
	 */
	public void fireMessagesListLoaded(String error){
		
		DataLoadedEvent dle = null;
		dle = new DataLoadedEvent(this, error);
		Iterator<IMessagesListLoaded> it = messagesListLoadedListeners.listIterator();
		while (it.hasNext()){
			 it.next().messagesListLoaded(dle);
		}
	}
	/********************************************************/
	
	
	
	/******************MessagePosted*****************/
	public synchronized void addMessagePostedListener(IMessagePosted listener){
		
		messagePostedListeners.add(listener);
	}
	
	
	public synchronized void removeMessagePostedListener(IMessagePosted listener){
		
		messagePostedListeners.remove(listener);
	}
	
	
	/**
	 * Fires all the Events for all the listener subscribed
	 */
	public void fireMessagePosted(String error){
		
		DataLoadedEvent dle = null;
		dle = new DataLoadedEvent(this, error);
		Iterator<IMessagePosted> it = messagePostedListeners.listIterator();
		while (it.hasNext()){
			 it.next().messagePosted(dle);
		}
	}
	/********************************************************/
	

	//GET method
	public String getConversationList(String userId, String signature)
	{
		return "<CommunicatorUri xmlns:i='http://www.w3.org/2001/XMLSchema-instance'>"+
			"<TimeToLive>168</TimeToLive>  <Uri><![CDATA[https://comm-movisol-com.s3.amazonaws.com/cvns/%7B/C/O/%7BCONVERSATIONID%7D.xml?AWSAccessKeyId=01QNJ366YT36W5AGERR2&Expires=1294067849&Signature=P7Hh98RJw8P%2BLkjgi3%2FR3gWHBp8%3D]]></Uri>"+
			"</CommunicatorUri>";
	}
	
	public String getXMLfromUri(String conversationsListUri)
	{
		return "<CommunicatorRoot>"+
				  "<Conversations>"+
				    "<Conversation ConversationId='0B0F2DDB1DF8519E112124B941E93CEC' Uri='https://comm-movisol-com.s3.amazonaws.com/cvns/0/B/0/0B0F2DDB1DF8519E112124B941E93CEC.xml?AWSAccessKeyId=01QNJ366YT36W5AGERR2&amp;Expires=1319798881&amp;Signature=gDvoBVCmmzHBKytJxM1AvcQTnVc%3D' DateLastModified='2011-10-21T10:47:40.24Z'>"+
				      "<LastMessage><![CDATA[Prueba]]></LastMessage>"+
				      "<Contacts>"+
				        "<Contact ContactId='a43e8919-506d-4d5d-807d-49817da289ed'>"+
				          "<Name><![CDATA[Kerchai]]></Name>"+
				          "<Email><![CDATA[demian@movisol.com]]></Email>"+
				        "</Contact>"+
				      "</Contacts>"+
				    "</Conversation>"+
				    "<Conversation ConversationId='7CA13002C674D8C8879B19EE8C8155C4' Uri='https://comm-movisol-com.s3.amazonaws.com/cvns/7/C/A/7CA13002C674D8C8879B19EE8C8155C4.xml?AWSAccessKeyId=01QNJ366YT36W5AGERR2&amp;Expires=1319798881&amp;Signature=EsDVwzuT9wPhOH%2BMQ65%2Bk5%2FFklI%3D' DateLastModified='2011-10-20T12:08:21.363Z'>"+
				      "<LastMessage><![CDATA[Ghhhgggggggggggggggggggggggggggggggghgggggggggggggggg]]></LastMessage>"+
				      "<Contacts>"+
				        "<Contact ContactId='a2d98db7-aa3f-454f-b6d9-bc3a25fd71c8'>"+
				          "<Name><![CDATA[]]></Name>"+
				          "<Email><![CDATA[marta@movisol.com]]></Email>"+
				        "</Contact>"+
				        "<Contact ContactId='5f3a004c-727a-4069-993c-1e25b14f7e23'>"+
				          "<Name><![CDATA[]]></Name>"+
				          "<Email><![CDATA[antonio.santiago@gmail.com]]></Email>"+
				        "</Contact>"+
				      "</Contacts>"+
				    "</Conversation>"+
				  "</Conversations>"+
				"</CommunicatorRoot>";
		
	}
	
	//GET method
	public String getMessageList(String conversationId)
	{
		URL url;
		String result = null;
		BufferedReader br = null;
		try {
			url = new URL(HelperUtils.getConfigParam("FQDNC", context)+ "/Service.svc/Conversation/"+ conversationId + "/");
			URLConnection c =  url.openConnection();
			c.setDoOutput(true);
			c.connect();
			InputStreamReader ins = new InputStreamReader(c.getInputStream());

			
			br = new BufferedReader(ins);
			StringBuffer sb = new StringBuffer();

			//Guardamos el stream recibido			
			String len1;
			while ((len1 = br.readLine()) != null) {
				sb.append(len1);
			}
			result = sb.toString();

			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (ProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}finally {
	            if (br != null) {
	                try {
	                	br.close();
	                } catch (IOException ex) {
	                    System.out.println("Problema al cerrar el objeto lector");
	                }
	            }
		}

		return result;
	}
	
	public String postMessage(CommunicatorRoot message, String userId)
	{
		return "<CommunicatorRoot xmlns:i='http://www.w3.org/2001/XMLSchema-instance'>"+
				  "<Messages>"+
				    "<Message>"+
				      "<MessagePublicId>179b6aba-b6a7-4443-81a2-c66de035bdac</MessagePublicId>"+
				      "<SequenceNumber>5</SequenceNumber>"+
				    "</Message>"+
				  "</Messages>"+
				"</CommunicatorRoot>";
	}
	

}
